package service

import (
	"context"
	"database/sql"

	dbmodel "gitee.com/hp-huiw/family-expense-api/internal/db/model"
	"gitee.com/hp-huiw/family-expense-api/internal/dto"
	"gitee.com/hp-huiw/family-expense-api/internal/repository"
	"gitee.com/hp-huiw/my-go-core/util"
)

type AppErrorReportService interface {
	Save(ctx context.Context, data *dto.AppErrorReportRequest) error
}

// NewAppErrorReportService creates a new AppErrorReportService.
func NewAppErrorReportService(db *sql.DB) AppErrorReportService {
	return &appErrorReportService{
		appErrorReportRepository: repository.NewAppErrorReportRepository(db),
	}
}

// Save saves error report sent from app.
func (s *appErrorReportService) Save(ctx context.Context, data *dto.AppErrorReportRequest) error {
	report := &dbmodel.AppErrorReport{
		ID:           util.GenerateUUIDWithoutDashes(),
		SystemInfo:   data.SystemInfo.String(),
		StackTrace:   data.StackTrace,
		ErrorMessage: data.ErrorMessage,
		Username:     data.Username,
		DeviceInfo:   util.AnyPtr(data.DeviceInfo.String()),
	}

	return s.appErrorReportRepository.Insert(ctx, report)
}

// Container of AppErrorReportService functions.
type appErrorReportService struct {
	appErrorReportRepository repository.AppErrorReportRepository
}
